# -*- coding: utf-8 -*-
# Author   : ZhangQing
# Time     : 2025-08-04 23:40
# File     : file.py
# Project  : codebuddy_craft
# Desc     : 文件模型

# backend/models/file.py
from sqlalchemy import Column, String, Text, ForeignKey, DateTime, Integer, Boolean, JSON
from sqlalchemy.orm import relationship
from sqlalchemy.sql import func
from datetime import datetime
import uuid

from backend.database.connection import Base


class File(Base):
    """文件模型 📄"""
    __tablename__ = "files"

    id = Column(String(36), primary_key=True, default=lambda: str(uuid.uuid4()))
    name = Column(String(255), nullable=False)
    path = Column(String(500), nullable=False)  # 项目内的相对路径
    content = Column(Text)

    # 文件信息
    file_type = Column(String(50))  # py, js, html, etc.
    encoding = Column(String(20), default="utf-8")
    size = Column(Integer, default=0)  # 字节大小
    lines = Column(Integer, default=0)  # 行数

    # 文件状态
    is_binary = Column(Boolean, default=False)
    is_hidden = Column(Boolean, default=False)

    # 版本控制
    version = Column(Integer, default=1)
    checksum = Column(String(64))  # SHA256校验和

    # 元数据
    file_metadata = Column(JSON, default={})

    # 关联项目
    project_id = Column(String(36), ForeignKey("projects.id"), nullable=False)

    # 时间戳
    created_at = Column(DateTime(timezone=True), server_default=func.now())
    updated_at = Column(DateTime(timezone=True), onupdate=func.now())
    last_accessed_at = Column(DateTime(timezone=True))

    # 关系
    project = relationship("Project", back_populates="files")

    def __repr__(self):
        return f"<File(id={self.id}, name={self.name}, path={self.path})>"

    def to_dict(self, include_content=False):
        """转换为字典"""
        result = {
            'id': self.id,
            'name': self.name,
            'path': self.path,
            'file_type': self.file_type,
            'encoding': self.encoding,
            'size': self.size,
            'lines': self.lines,
            'is_binary': self.is_binary,
            'is_hidden': self.is_hidden,
            'version': self.version,
            'checksum': self.checksum,
            'metadata': self.file_metadata,
            'project_id': self.project_id,
            'created_at': self.created_at.isoformat() if self.created_at else None,
            'updated_at': self.updated_at.isoformat() if self.updated_at else None,
            'last_accessed_at': self.last_accessed_at.isoformat() if self.last_accessed_at else None
        }

        if include_content:
            result['content'] = self.content

        return result

    @property
    def extension(self):
        """获取文件扩展名"""
        return self.name.split('.')[-1].lower() if '.' in self.name else ''

    @property
    def is_code_file(self):
        """判断是否为代码文件"""
        code_extensions = {
            'py', 'js', 'ts', 'jsx', 'tsx', 'html', 'css', 'scss', 'less',
            'rs', 'go', 'java', 'cpp', 'c', 'h', 'hpp', 'cs', 'php',
            'rb', 'swift', 'kt', 'scala', 'clj', 'elm', 'hs', 'ml',
            'json', 'yaml', 'yml', 'toml', 'ini', 'cfg', 'xml'
        }
        return self.extension in code_extensions

